//
//  YSReadTableViewController.m
//  YSBookRead
//
//  Created by MOLBASE on 2018/11/14.
//  Copyright © 2018年 YangShen. All rights reserved.
//

#import "YSReadTableViewController.h"
#import "YSReaderSetting.h"
#import "YSStatusView.h"
#import "YSReadView.h"
#import "YSBookChapterContentModel.h"
#import "YSReadRecordModel.h"
#import "MJRefresh.h"
#import "YSHUDManager.h"

@interface YSReadTableViewController () <UITableViewDataSource, UITableViewDelegate>
{
    BOOL _isDragging;
}

/// 背景图片
@property (nonatomic, weak) UIImageView *backImageView;
/// TableView
@property (nonatomic, weak) UITableView *tableView;
/// 顶部状态栏
@property (nonatomic, weak) UILabel *topStatusLabel;
/// 底部状态栏
@property (nonatomic, weak) YSStatusView *bottomStatusView;

/// 阅读列表
@property (nonatomic, strong) NSMutableArray *dataArray;
/// 记录当前已经加载或正在加载的章节列表 以免重复操作
@property (nonatomic, strong) NSMutableArray *willLoadDataIndex;

@end

@implementation YSReadTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    // 添加子控件
    [self setupSubViews];
}

- (void)setupSubViews {

    UIImageView *backImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    backImageView.image = [YSReaderSetting shareReaderSettings].themeImage;
    [self.view addSubview:backImageView];
    self.backImageView = backImageView;

    UILabel *topStatusLabel = [[UILabel alloc] init];
    topStatusLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    topStatusLabel.textColor = [[YSReaderSetting shareReaderSettings] otherTextColor];
    topStatusLabel.font = [UIFont systemFontOfSize:12];
    topStatusLabel.frame = CGRectMake(kYSReaderXSpace, 0, self.view.frame.size.width - 2 * kYSReaderXSpace, kYSReaderYSpace);
    [self.view addSubview:topStatusLabel];
    self.topStatusLabel = topStatusLabel;

    YSStatusView *bottomStatusView = [[YSStatusView alloc] initWithFrame:CGRectMake(kYSReaderXSpace, self.view.frame.size.height - kYSReaderYSpace, self.view.frame.size.width - 2 * kYSReaderXSpace, kYSReaderYSpace)];
    bottomStatusView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:bottomStatusView];
    self.bottomStatusView = bottomStatusView;

    UITableView *tableView = [[UITableView alloc] initWithFrame:YSReaderFrame() style:UITableViewStylePlain];
    self.tableView = tableView;
    tableView.backgroundColor = [UIColor clearColor];
    tableView.showsVerticalScrollIndicator = NO;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.estimatedRowHeight = 0;
    tableView.estimatedSectionFooterHeight = 0;
    tableView.estimatedSectionHeaderHeight = 0;
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.scrollsToTop = NO;
    [self.view addSubview:tableView];

    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        YSBookChapterContentModel *chaperContent = self.dataArray.firstObject;
        NSInteger chapterIndex = chaperContent.chapterIndex;

        // 预加载数据
        // 加载上一章
        if (chapterIndex > 0 && ![self.willLoadDataIndex containsObject:@(chapterIndex-1)]) {
            [self.willLoadDataIndex addObject:@(chapterIndex-1)];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                YSBookChapterContentModel *prevChaperContent = self.readOperation.chapterContentList[chapterIndex-1];
                [prevChaperContent updateContentPaging];

                if (!prevChaperContent.haveCache) {

                    [self.readOperation getChapterContentWithChapter:chapterIndex-1 needPadingContent:YES completion:^{

                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.dataArray insertObject:prevChaperContent atIndex:0];
                            [self.tableView reloadData];
                            self.tableView.contentOffset = CGPointMake(0, self.tableView.contentOffset.y + prevChaperContent.pageCount * YSReaderFrame().size.height);

                            [self.readOperation autoLoadNextChapters:chapterIndex-1-1];

                            [tableView.mj_header endRefreshing];
                        });

                    } failure:^(NSString *msg) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.willLoadDataIndex removeObject:@(chapterIndex-1)];
                            [YSHUDManager showHUDMessage:msg afterDelay:1];
                            [tableView.mj_header endRefreshing];
                        });
                    }];

                } else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.dataArray insertObject:prevChaperContent atIndex:0];
                        [self.tableView reloadData];
                        self.tableView.contentOffset = CGPointMake(0, self.tableView.contentOffset.y + prevChaperContent.pageCount * YSReaderFrame().size.height);
                        [self.readOperation autoLoadNextChapters:chapterIndex-1-1];
                        [tableView.mj_header endRefreshing];
                    });
                }
            });
        }

    }];

    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;

    tableView.mj_header = header;


    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"进入footer");
        YSBookChapterContentModel *chaperContent = self.dataArray.lastObject;
        NSInteger chapterIndex = chaperContent.chapterIndex;
        // 下一章
        if (chapterIndex+1 < self.readOperation.chapterContentList.count && ![self.willLoadDataIndex containsObject:@(chapterIndex+1)]) {
            [self.willLoadDataIndex addObject:@(chapterIndex+1)];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                YSBookChapterContentModel *nextChaperContent = self.readOperation.chapterContentList[chapterIndex+1];
                [nextChaperContent updateContentPaging];

                if (!nextChaperContent.haveCache) {
                    [self.readOperation getChapterContentWithChapter:chapterIndex+1 needPadingContent:YES completion:^{

                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.dataArray addObject:nextChaperContent];
                            [self.tableView reloadData];
                            [self.readOperation autoLoadNextChapters:chapterIndex+1+1];
                            [tableView.mj_footer endRefreshing];
                        });

                    } failure:^(NSString *msg) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [self.willLoadDataIndex removeObject:@(chapterIndex+1)];
                            [YSHUDManager showHUDMessage:msg afterDelay:1];
                            [tableView.mj_footer endRefreshing];
                        });
                    }];
                } else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.dataArray addObject:nextChaperContent];
                        [self.tableView reloadData];
                        [self.readOperation autoLoadNextChapters:chapterIndex+1+1];
                        [tableView.mj_footer endRefreshing];
                    });
                }
            });
        }
    }];

    footer.stateLabel.hidden = YES;
    footer.labelLeftInset = -300;

    tableView.mj_footer = footer;

    [self prepareData];
}

- (void)prepareData {
    self.dataArray = [NSMutableArray array];
    self.willLoadDataIndex = [NSMutableArray array];

    [self.dataArray addObject:self.readOperation.chapterContentList[self.readOperation.readRecord.readChapter]];
    [self.willLoadDataIndex addObject:@(self.readOperation.readRecord.readChapter)];

    // 滚动到阅读记录
    self.tableView.contentOffset = CGPointMake(self.tableView.contentOffset.x, YSReaderFrame().size.height * self.readOperation.readRecord.readPage);

    YSBookChapterContentModel *chapterContent = self.readOperation.chapterContentList[self.readOperation.readRecord.readChapter];
    [self setTitleLabels:chapterContent page:self.readOperation.readRecord.readPage];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    YSBookChapterContentModel *chapterContentModel = self.dataArray[section];
    return chapterContentModel.pageCount;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YSReadViewCell *cell = [YSReadViewCell cellWithTableView:tableView];
    YSBookChapterContentModel *chapterContentModel = self.dataArray[indexPath.section];
    cell.readView.content = [chapterContentModel getStringWith:indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return YSReaderFrame().size.height;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    _isDragging = YES;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    _isDragging = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (!_isDragging) { return; }

    // 没有cell
    if (self.tableView.indexPathsForVisibleRows.count == 0) { return; }

    CGRect rect = YSReaderFrame();

    // 显示章节Cell IndexPath
    NSIndexPath *indexPath = [self.tableView indexPathsForRowsInRect:CGRectMake(0, self.tableView.contentOffset.y, rect.size.width, rect.size.height)].firstObject;

    YSBookChapterContentModel *chapterContent = self.dataArray[indexPath.section];
    // page
    NSInteger page = indexPath.row;

    [self setTitleLabels:chapterContent page:page];
}

- (void)setTitleLabels:(YSBookChapterContentModel *)chapterContent page:(NSInteger)page {

    if (page >= chapterContent.pageCount) {
        page = chapterContent.pageCount - 1;
    }

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 修改阅读记录

        [self.readOperation updateReadRecordWithChapter:chapterContent.chapterIndex page:page];

        dispatch_async(dispatch_get_main_queue(), ^{
            // 修改title
            self.topStatusLabel.text = chapterContent.chapterName;
            self.bottomStatusView.titleLabel.text = [NSString stringWithFormat:@"%zd/%zd", page+1, chapterContent.pageCount];
        });
    });
}

@end
